﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using PagedList;
using SIG.Service;
using SIG.Model;
using System;

using SIG.WebMVC.Filters;
using SIG.Infrastructure.Configs;
using SIG.Model.Enums;
using SIG.ViewModel;
using SIG.Infrastructure.Extensions;
using System.Xml.Linq;
using SIG.Infrastructure.Helper;
using SIG.ViewModel.Admin.FQAs;
using SIG.Model.FQAs;
using SIG.InputModel.Admin.FQAs;
using SIG.Resources.Admin;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]   
    public class QuestionController : BaseController
    {
        private readonly IQuestionCategoryService _categoryService;
        private readonly IQuestionService _questionService;
        private readonly IPageMetaService _pageMetaService;
        private readonly IMapper _mapper;

        public QuestionController(IQuestionCategoryService categoryService,IQuestionService questionService, IPageMetaService pageMetaService, IMapper mapper)
        {
            _categoryService = categoryService;
            _questionService = questionService;
            _pageMetaService = pageMetaService;
            _mapper = mapper;


        }
        #region 常见问题
        

    [HttpGet]
        public ActionResult Index(int? page, int? categoryId,string Keyword)
        {

            var questionListVM = new QuestionListVM();

            questionListVM.CategoryId = categoryId??0;
            questionListVM.PageIndex = (page ?? 1) - 1;
            questionListVM.PageSize = SettingsManager.Question.PageSize;
            questionListVM.Keyword = Keyword;

            int count;
            var questions = _questionService.GetPagedElements(questionListVM.PageIndex, questionListVM.PageSize, questionListVM.Keyword, questionListVM.CategoryId,out count);          

            var questionDtos = _mapper.Map<List<Question>, List<QuestionVM>>(questions);
                      
            //questionListVM.Questions = questionDtos;
            questionListVM.TotalCount = count;  

            var categoryList = _categoryService.GetAll().OrderByDescending(c => c.Importance).ToList();
            var categories = new SelectList(categoryList, "Id", "Title");
            ViewBag.Categories = categories;

            questionListVM.Questions = new StaticPagedList<QuestionVM>(questionDtos, questionListVM.PageIndex + 1, questionListVM.PageSize, questionListVM.TotalCount);
           // ViewBag.OnePageOfQuestions = questionsAsIPagedList;

            ViewBag.PageSizes = new SelectList(Site.PageSizes());

            return View(questionListVM);
          
        }


        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/QuestionSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }


        public ActionResult Add()
        {
           var question = new QuestionIM { Active = true};

           var categorys = _categoryService.GetAll().OrderByDescending(m=>m.Importance).ToList(); 
           var lCategorys = new SelectList(categorys, "Id", "Title");
                         
            ViewBag.Categories = lCategorys;
            return View(question);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Add(QuestionIM question)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage()); 
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
           
                var newQuestion = _mapper.Map<QuestionIM, Question>(question);
                _questionService.Create(newQuestion); 

                AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Question));         
                return Json(AR, JsonRequestBehavior.DenyGet);

            }catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }


        }

      [HttpGet]
        public ActionResult Edit(int Id)
        {
            var vQuestion = _questionService.GetById(Id);
            if(vQuestion == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }
            
            
            var editQuestion = _mapper.Map<Question, QuestionIM>(vQuestion);

 
            var categorys = _categoryService.GetAll().OrderByDescending(m => m.Importance).ToList();
            var lCategorys = new SelectList(categorys, "Id", "Title");

            ViewBag.Categories = lCategorys;

            return View(editQuestion);
          
          
        }

        [HttpPost]
        [ValidateInput(false)] 
        [ValidateAntiForgeryToken]
        public JsonResult Edit(QuestionIM question)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                var editQuestion = _mapper.Map<QuestionIM, Question>(question);
                _questionService.Update(editQuestion);

                      

                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Question));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

          
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult IsActive(int id)
        {

            Question vQuestion = _questionService.GetById(id);            

            try
            {
                vQuestion.Active = !vQuestion.Active;
                _questionService.Update(vQuestion);

                var vm = _mapper.Map<QuestionVM>(vQuestion);

                AR.Data = RenderPartialViewToString("_QuestionItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Question));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }

     


        [HttpPost]       
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            Question vQuestion = _questionService.GetById(id);

            if (vQuestion == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            _questionService.Delete(vQuestion);

            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Question));
            return Json(AR, JsonRequestBehavior.DenyGet);           

        }

        #endregion


    }
}
